package org.example.common.datasource.handler;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.google.common.collect.Sets;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.example.common.core.utils.StringUtils;
import org.example.common.datasource.config.properties.TenantProperties;
import org.example.common.datasource.utils.TenantHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * 多租戶
 */
public class MyTenantLineHandler implements TenantLineHandler {
    private static Logger  log= LoggerFactory.getLogger(MyTenantLineHandler.class);

    private final Set<String> ignoreTables =Sets.newHashSet();

    public MyTenantLineHandler(TenantProperties properties) {
        properties.getExcludes().forEach(table -> {
            ignoreTables.add(table.toLowerCase());
            ignoreTables.add(table.toUpperCase());
        });
    }

    @Override
    public Expression getTenantId() {
        String tenantId= TenantHelper.getTenantId();
        if (StringUtils.isBlank(tenantId)) {
            log.error("无法获取有效的租户id -> Null");
            return new NullValue();
        }
        return new StringValue(tenantId);
    }

    @Override
    public boolean ignoreTable(String tableName) {
        String tenantId = TenantHelper.getTenantId();
        // 判断是否有租户
        if (StringUtils.isNotBlank(tenantId)) {
            // 忽略多租户的表
            return CollUtil.contains(ignoreTables, tableName);
        }
        return true;
    }
}
